﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using PMKB_Repository;
using PMKB_DAL;
using System.ComponentModel.Composition;
using Plugin_Interfaces;



namespace PMKB_Web.Controllers
{
    [Export(typeof(Controller))]
    public partial class AddFileController : Controller, AddObject
    {
        private readonly string Connection;
        private readonly string FolderSave;
        private const string saved="saved";
        public AddFileController()
            : this("","")
        {
            
        }
        
        public AddFileController(string connectionString, string folderSave)
            : base()
        {
            Connection = connectionString;
            FolderSave = folderSave;
        }
        public virtual ActionResult Index(){
            var obj = TempData[saved];
            if(obj != null && !string.IsNullOrEmpty(obj.ToString()))
            {
                    ViewBag.saved=obj.ToString();
            }
            else{
                    ViewBag.saved="";
            }
            //TODO : see this viewbag into the view!
            return View("InputFile");
        }
        public event EventHandler<EventString> ObjectSaved;
        [HttpPost]
        public virtual ActionResult Index(HttpPostedFileWrapper NewFile)
        {
            
            string ConnectionName=Connection;
            //TODO: remove hard coded files
            string saveFileName = Path.GetFileName(NewFile.FileName);
            DateTime dt=DateTime.Now;
            string FileName=Path.Combine(FolderSave,dt.ToString("yyyyMMdd_HHmmss")+"_"+ saveFileName );
            NewFile.SaveAs(FileName);
            if (ObjectSaved != null)
                ObjectSaved(this, new EventString() { Value = FileName });

            
            TempData.Add(saved, "saved " + saveFileName);
            return RedirectToAction("Index");

        }
        public ActionResult View(long id)
        {
            LinkAddOrEdit a=new LinkAddOrEdit();
            a.ConnectionName = Connection;
            var link=a.LoadLink(id);
            var name=link.LinkCreationDate.Value.ToString("yyyyMMdd_HHmmss")+"_"+ link.LinkName ;
            var pathFile=Path.Combine(FolderSave,name);
            return File(pathFile,"application/octet-stream",name);
        }

        public Type T
        {
            get
            {
                return typeof(Link);   
            }
            
        }

        public string Name
        {
            get { return "Add File"; }
        }
    }
}
